using System;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using OpenWaves.Web;

namespace OpenWaves.ActivityFeed.Web.Controls
{
    public abstract class ListPlaceHolderBase : WebControl
    {
        protected ListPlaceHolderBase() : base("ul") { }

        protected ActivityFeedBase ParentActivityFeedBase
        {
            get { return this.GetAncestors().OfType<ActivityFeedBase>().First(); }
        }

        protected static void WriteAttributes(HtmlTextWriter writer, string listProperty, ListClientSettings settings, string contentControlClientId, string cssClass = null)
        {
            var eventBeforeRemove = string.IsNullOrEmpty(settings.BeforeRemove) ? "" : ",beforeRemove: " + settings.BeforeRemove;
            var eventAfterRender = string.IsNullOrEmpty(settings.AfterRender) ? "" : ",afterRender: " + settings.AfterRender;
            var eventAfterAdd = string.IsNullOrEmpty(settings.AfterAdd) ? "" : ",afterAdd: " + settings.AfterAdd;
            var additionalBindings = string.Empty;
            if (settings.AdditionalBindings != null && settings.AdditionalBindings.Any())
            {
                additionalBindings = String.Join("",
                                                 settings.AdditionalBindings.Select(
                                                     b =>
                                                     string.Format(CultureInfo.InvariantCulture, ", {0}: {1}", (b.Name ?? "").Trim(),
                                                                   (b.Expression ?? ""))).ToArray());
            }

            var dataBind = string.Format(CultureInfo.InvariantCulture,
                                         "template: {{name: '{1}', foreach: {0}{2}{3}{4}}}{5}",
                                         listProperty, contentControlClientId, eventBeforeRemove, eventAfterRender,
                                         eventAfterAdd, additionalBindings);
            writer.AddAttribute("data-bind", dataBind);

            if (!string.IsNullOrEmpty(cssClass))
            {
                writer.AddAttribute("class", cssClass);
            }
        }
    }
}